package utils

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"os"
	"strings"
	"time"
	"vueBasic/global"
)

// 判断目录是否存在
func PathExists(path string) (bool, error) {
	fi, err := os.Stat(path)
	if err == nil {
		if fi.IsDir() {
			return true, nil
		}
		return false, errors.New("存在同名文件")
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

// 创建目录
func CreateDir(path string) error {
	if ok, _ := PathExists(path); !ok { // 判断是否有Director文件夹
		err := os.MkdirAll(path, os.ModePerm)
		return err
	}
	return nil
}

// 创建上传文件存储目录
func CreatePath(savepath string) bool {
	if err := CreateDir(global.CONF.Upload.AccessPath + savepath); err != nil {
		panic(err)
	}
	return true
}

// 获取文件保存目录
func GetSavePath(c *gin.Context) string {
	applicationName := strings.Split(strings.TrimLeft(c.Request.RequestURI, "/"), "/")[0]
	savepath := fmt.Sprintf("/%s/%s/%s", global.CONF.Upload.UploadPath, applicationName, time.Now().Format("200601"))
	return savepath
}
